package com.song.flowable.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.flowable.idm.api.Group;
import org.flowable.idm.engine.IdmEngineConfiguration;
import org.flowable.idm.engine.impl.GroupQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntity;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityManagerImpl;
import org.flowable.idm.engine.impl.persistence.entity.data.GroupDataManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;


public class CustomGroupEntityManager extends GroupEntityManagerImpl {

    @Autowired
    private RestTemplate restTemplate;

    public CustomGroupEntityManager(IdmEngineConfiguration idmEngineConfiguration, GroupDataManager groupDataManager) {
        super(idmEngineConfiguration, groupDataManager);
    }

    @Override
    public GroupEntity findById(String entityId) {
        GroupEntity groupEntity = new GroupEntityImpl();
        groupEntity.setId("123456");
        groupEntity.setName("群组一");
        return groupEntity;
    }
    //TODO 改成redis查
    @Override
    public List<Group> findGroupByQueryCriteria(GroupQueryImpl query) {
        String baseUrl = "http://bmp-user/flowable/getGroupList";
        Map<String, Object> maps = new HashMap<>();
        maps.put("groupId", query.getId());
        maps.put("userId", query.getUserId());
        maps.put("type", query.getType());
        String url = "";
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        JSONArray groupList = (JSONArray) JSONObject.parseObject(response.getBody()).get("response");
        List<Group> groups = new ArrayList<>();
        groupList.stream().forEach(group->{
            GroupEntity groupEntity = new GroupEntityImpl();
            groupEntity.setId(((JSONObject)group).getString("id"));
            groupEntity.setName(((JSONObject)group).getString("name"));
            groupEntity.setType(((JSONObject)group).getString("type"));
            groups.add(groupEntity);
        });
        return groups;
    }

    @Override
    public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
        return 1l;
    }


}
